package com.wellsoft.mobileoa.utils.widget;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import com.wellsoft.mobileoa.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

import com.wellsoft.mobileoa.utils.BaseActivity;
import com.wellsoft.mobileoa.utils.BaseView;
import com.wellsoft.mobileoa.utils.BaseWidget;
import com.wellsoft.mobileoa.utils.SystemConfig;
import com.wellsoft.mobileoa.wsmodel.WSOA_PageField;
import com.wellsoft.mobileoa.wsmodel.WSOA_PostField;
import com.wmobile.utils.ServiceResponse;

public class DatetimeWidget extends BaseWidget {
	private TextView fieldTitleTv;
	private Button fieldValueBtn;
	private SimpleDateFormat datetimeSdf = null;

	public DatetimeWidget(WSOA_PageField field, BaseView baseView) {
		this.field = field;
		this.baseView = baseView;
		if (field.getFieldType().equals("datetime")) {
			datetimeSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		} else if (field.getFieldType().equals("date")) {
			datetimeSdf = new SimpleDateFormat("yyyy-MM-dd");
		} else if (field.getFieldType().equals("time")) {
			datetimeSdf = new SimpleDateFormat("HH:mm");
		}
	}

	@Override
	public View getView() {
		view = LayoutInflater.from(baseView.getBaseActivity()).inflate(R.layout.datetimewidget,
				null);
		fieldTitleTv = (TextView) view
				.findViewById(R.id.datetimewidget_fieldtitletv);
		fieldTitleTv.setText(field.getFieldTitle());
		fieldValueBtn = (Button) view
				.findViewById(R.id.datetimewidget_fieldvaluebtn);
		fieldValueBtn.setText(field.getFieldValue());
		fieldValueBtn.setOnClickListener(onDateTimeListener);
		return view;
	}

	OnClickListener onDateTimeListener = new OnClickListener() {
		AlertDialog dialog;

		@Override
		public void onClick(View v) {
			Date textValue = null;

			if (!SystemConfig.stringIsNullOrEmpty(fieldValueBtn.getText()
					.toString())) {
				try {
					textValue = datetimeSdf.parse(fieldValueBtn.getText()
							.toString());
				} catch (ParseException e) {
					textValue = new Date();
					e.printStackTrace();
				}
			} else {
				textValue = new Date();
			}
			Calendar nowCalendar = Calendar.getInstance();
			nowCalendar.setTime(textValue);

			View datetimeView = LayoutInflater.from(baseView.getBaseActivity()).inflate(
					R.layout.datetimepickwidget, null);

			DatePicker dateDp = (DatePicker) datetimeView
					.findViewById(R.id.datetimepickwidget_datepicker);
			dateDp.init(nowCalendar.get(Calendar.YEAR),
					nowCalendar.get(Calendar.MONTH),
					nowCalendar.get(Calendar.DAY_OF_MONTH), null);

			Button datetime_clear_btn = (Button) datetimeView
					.findViewById(R.id.datetimepickwidget_clear_btn);
			datetime_clear_btn.setOnClickListener(clearListener);

			TimePicker timeDp = (TimePicker) datetimeView
					.findViewById(R.id.datetimepickwidget_timepicker);
			
			if (field.getFieldType().equals("date")) {
				timeDp.setVisibility(View.GONE);
			} else if (field.getFieldType().equals("time")) {
				dateDp.setVisibility(View.GONE);
			}
			dialog = showAlertDialog(baseView.getBaseActivity(), "选择时间", datetimeView,
					flightDateTimeConfirmListener, closeAlertDialogListener);
		}

		OnClickListener clearListener = new OnClickListener() {

			@Override
			public void onClick(View v) {

				fieldValueBtn.setText("");
				dialog.dismiss();
			}

		};
	};

	DialogInterface.OnClickListener flightDateTimeConfirmListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			AlertDialog alertDialog = (AlertDialog) dialog;
			StringBuffer stringBuffer = new StringBuffer();

			if (field.getFieldType().equals("datetime")
					|| field.getFieldType().equals("date")) {
				DatePicker datepickerDp = (DatePicker) alertDialog
						.findViewById(R.id.datetimepickwidget_datepicker);
				int year = datepickerDp.getYear();
				if (year < 10) { // 判断年是否小于10
					stringBuffer.append("0" + year);
				} else {
					stringBuffer.append(year + "");
				}

				int month = (datepickerDp.getMonth() + 1);
				if (month < 10) { // 判断月是否小于10
					stringBuffer.append("-" + "0" + month);
				} else {
					stringBuffer.append("-" + month + "");
				}

				int dayOfMonth = datepickerDp.getDayOfMonth();
				if (dayOfMonth < 10) { // 判断日是否小于10
					stringBuffer.append("-" + "0" + dayOfMonth);
				} else {
					stringBuffer.append("-" + dayOfMonth + "");
				}
				stringBuffer.append(" ");
			}

			if (field.getFieldType().equals("datetime")
					|| field.getFieldType().equals("time")) {
				TimePicker timepickerTp = (TimePicker) alertDialog
						.findViewById(R.id.datetimepickwidget_timepicker);
				int hour = timepickerTp.getCurrentHour();
				if (hour < 10) { // 判断年是否小于10
					stringBuffer.append("0" + hour);
				} else {
					stringBuffer.append(hour + "");
				}

				int min = (timepickerTp.getCurrentMinute());
				if (min < 10) { // 判断小时是否小于10
					stringBuffer.append(":" + "0" + min);
				} else {
					stringBuffer.append(":" + min + "");
				}
			}
			DatetimeWidget.this.setValue(stringBuffer.toString().trim());
		}

	};

	/**
	 * 关闭对话框
	 */
	protected DialogInterface.OnClickListener closeAlertDialogListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();
		}

	};

	/**
	 * 弹出对话框
	 */
	protected AlertDialog showAlertDialog(Context context, String title,
			View view, DialogInterface.OnClickListener onConfirmClickListener,
			DialogInterface.OnClickListener onCancelClickListener) {
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
		dialogBuilder.setTitle(title);
		if (view != null) {
			dialogBuilder.setView(view);
		}
		if (onConfirmClickListener != null) {
			dialogBuilder.setPositiveButton("确认", onConfirmClickListener);
		}
		if (onCancelClickListener != null) {
			dialogBuilder.setNegativeButton("取消", onCancelClickListener);
		}
		AlertDialog alertDialog = dialogBuilder.create();
		alertDialog.setCanceledOnTouchOutside(false);
		alertDialog.show();
		return alertDialog;
	}

	@Override
	public WSOA_PostField getValue() {
		List<String> listValue = new ArrayList<String>();
		WSOA_PostField postfield = new WSOA_PostField();
		postfield.setFieldName(field.getFieldName());
		listValue.add(fieldValueBtn.getText().toString());
		postfield.setFieldValues(listValue);
		return postfield;
	}

	@Override
	public void setValue(Object widgetValue) {
		fieldValueBtn.setText(widgetValue.toString());
		baseView.setHasEdited(true);
		setHasEdited(true);
		setHasValided(false);
	}


	@Override
	public void resetWidget() {
		fieldValueBtn.setText("");
	}

	@Override
	public ServiceResponse checkValid() {
		String fieldValue = fieldValueBtn.getText().toString();
		if (field.getRequired() != null) {
			if (field.getRequired().equals("1")
					&& SystemConfig.stringIsNullOrEmpty(fieldValue)) {
				return new ServiceResponse(false, field.getFieldTitle()
						+ "不能为空！");
			}
		}
		return new ServiceResponse(true);
	}
}
